package com.yn.sample.util;

import com.yn.sample.domain.ConstantPoolItem;

import java.util.List;

public class ConstantPoolUtil {

    public static String getConstantPoolItemValue(List<ConstantPoolItem> constantPoolItems,
                                                  String poolItemId) {
        ConstantPoolItem constantPoolItem = constantPoolItems.stream()
                .filter(item -> item.getId().equalsIgnoreCase(poolItemId))
                .findFirst()
                .orElse(null);
        if (constantPoolItem == null) {
            throw new RuntimeException();
        }

        String value = constantPoolItem.getValue();
        /**
         * 如果包含#号，说明这是一个常量池item的id，我们要递归获取
         */
        if (!value.contains("#")) {
            return value;
        }

        /**
         * 包含#的情况下，有两种情况：
         * 一种格式如下：
         * #3 = String             #35            //  test user
         * ...
         * #35 = Utf8               test user
         *
         * 另一种的格式如下：
         * #36 = NameAndType        #13:#14        //  name:Ljava/lang/String;
         * #13 = Utf8               name
         * #14 = Utf8               Ljava/lang/String;
         */
        String[] idArray = value.split(":");
        if (idArray.length == 1) {
            return getConstantPoolItemValue(constantPoolItems, value);
        } else {
            String first = getConstantPoolItemValue(constantPoolItems, idArray[0]);
            String second = getConstantPoolItemValue(constantPoolItems, idArray[1]);
            return first + ":" + second;
        }

    }
}
